
package com.xmb.wcapi.util;

import com.alibaba.fastjson.JSONObject;
import com.xmb.wcapi.constant.GuardConstant;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URLEncoder;

/**
 * @description: 速通门接口调用http工具类
 */
public class UniHttpUtil {
    /**
     * 日志信息
     */
    private static final Logger logger = LoggerFactory.getLogger(UniHttpUtil.class);

    private static CookieStore cookieStore;

    public static CookieStore getCookieStore() {
        return cookieStore;
    }

    public static void setCookieStore(CookieStore cookieStore) {
        UniHttpUtil.cookieStore = cookieStore;
    }

    /**
     * 获取登录的cookie信息
     *
     * @return
     */
    public static CookieStore getCookieStore(String loginUrl, String user, String passwd) throws IOException {
        JSONObject loginParm = new JSONObject();
        if (null != user && null != passwd) {
            loginParm.put("Id", user);
            loginParm.put("Pwd", passwd);
        } else {
            logger.error("user or password can't be null");
            return null;
        }

        CookieStore cookieStore = new BasicCookieStore();
        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
        //创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

        //创建httpPost请求对象
        HttpPost httpPost = new HttpPost(loginUrl);
        httpPost.setHeader(HttpHeaders.CONTENT_TYPE, GuardConstant.CONTENT_TYPE_JSON);
        httpPost.setEntity(new StringEntity(loginParm.toString(), ContentType.APPLICATION_JSON));

        //执行请求
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost, localContext);
        HttpEntity entity = httpResponse.getEntity();
        //解析请求结果
        String response = EntityUtils.toString(entity, "UTF-8");
        UniResult uniResult = JSONObject.parseObject(response, UniResult.class);
        //资源关闭
        close(httpClient, httpResponse);
        if (uniResult == null || HttpStatus.SC_OK != uniResult.getErrCode()) {
            logger.error(" get cookieStore error,UniResult: {}", uniResult.toString());
            return null;
        } else {
            setCookieStore(cookieStore);
            logger.debug(" get cookieStore success.");
        }
        return cookieStore;
    }

    /**
     * 发送get请求
     *
     * @param httpUrl
     * @param json
     * @return
     * @throws IOException
     */
    public static UniResult sendHttpGetJson(String httpUrl, String json) throws IOException {
        String response = null;
        String params = null;
        HttpGet httpGet = null;
        if (json != null) {
            params = URLEncoder.encode(json, "UTF-8");
            httpGet = new HttpGet(httpUrl + params);
        } else {
            httpGet = new HttpGet(httpUrl);
        }
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        response = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        if (null == response) {
            return null;
        }
        //资源关闭
        close(httpClient, httpResponse);
        return JSONObject.parseObject(response, UniResult.class);
    }

    /**
     * 资源释放
     *
     * @param httpClient
     * @param httpResponse
     */
    public static void close(CloseableHttpClient httpClient, CloseableHttpResponse httpResponse) {
        // 释放资源
        if (httpResponse != null) {
            try {
                httpResponse.close();
            } catch (IOException e) {
                logger.error("{}", e);
            }
        }
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.error("{}", e);
            }
        }
    }

}
